﻿
using System;
using System.Collections.Generic;
using System.Configuration;
using System.IO;
using System.Web;
using System.Web.Mvc;
using AMG.Common.Utilities;
using AMG.UserForms.Service;
using AMG.UserForms.ViewModels;
using Uti.AMG.UserForms.Web.Infrastructure;

namespace AMG.UserForms.Web.Controllers
{
    public class ArchChangeController : ControllerBase
    {
        public ActionResult Index()
        {
            return View(new ArchitecturalChange());
        }

        /// <summary>
        /// The post action for the arch change request.  Calls service method to save/send request
        /// </summary>
        /// <param name="archChange"></param>
        /// <returns></returns>
        [HttpPost]
        public ActionResult Index(ArchitecturalChange archChange)
        {
            //Set list of uploaded files
            //If IE, get files from request
            if (Request.Browser.Browser.ToLower() == "firefox")
            {
                archChange.FileList = UploadedFilesInSession;
            }
            else 
            {
                archChange.FileList = new List<UploadedFile>();
                int index = 0;
                foreach(var file in Request.Files)
                {
                    var uploadedFile = new UploadedFile {FileName = Request.Files[index].FileName};
                    using (var binaryReader = new BinaryReader(Request.Files[index].InputStream))
                    {
                        uploadedFile.FileData = binaryReader.ReadBytes(Request.Files[index].ContentLength);
                    } 
                    archChange.FileList.Add(uploadedFile);
                    index++;
                }
            }
            
            //Perform the save
            var svc = new UserFormsAppService();
            svc.SubmitArchitecturalChangeRequest(archChange);

            //Clear list of files in session
            UploadedFilesInSession.Clear();

            return RedirectToAction("Index");
        }

        /// <summary>
        /// Adds file to uploaded files list in session, and returns html of file FileList view to render
        /// </summary>
        /// <param name="fileData"></param>
        /// <param name="fileName"></param>
        /// <returns></returns>
        public ActionResult AddFileToList(string fileData, string fileName)
        {
            //Trim off garbage and convert from base64 to bye array
            byte[] fileBytes = Convert.FromBase64String(fileData.Substring(fileData.IndexOf(",")+1));

            //Add this byte array to list in session
            List<UploadedFile> uploadedFiles = UploadedFilesInSession;
            uploadedFiles.Add(new UploadedFile { FileData = fileBytes, FileName = fileName });
            UploadedFilesInSession = uploadedFiles;

            return PartialView("FileList", uploadedFiles);
        }

        /// <summary>
        /// Removes a file from the list in session
        /// </summary>
        /// <param name="index"></param>
        /// <returns></returns>
        [CacheControl(HttpCacheability.NoCache), HttpGet]
        public ActionResult RemoveFileFromList(int index)
        {
            List<UploadedFile> uploadedFiles = UploadedFilesInSession;

            uploadedFiles.RemoveAt(index);

            UploadedFilesInSession = uploadedFiles;

            return PartialView("FileList", uploadedFiles);
        }

        /// <summary>
        /// Retains list of uploaded files in session
        /// </summary>
        private List<UploadedFile> UploadedFilesInSession
        {
            get
            {
                var uploadedFiles = new List<UploadedFile>();
                if (Session["UploadedFiles"] != null)
                {
                    uploadedFiles = (List<UploadedFile>)Session["UploadedFiles"];
                }
                return uploadedFiles;
            }
            set
            {
                Session["UploadedFiles"] = value;
            }
        }

        /// <summary>
        /// Based on the index of the image in the session list, returns a file content result to be rendered in browser
        /// </summary>
        /// <param name="index"></param>
        /// <returns></returns>
        [CacheControl(HttpCacheability.NoCache), HttpGet]
        public FileContentResult RenderImage(int index)
        {
            //Get the file in session at this index
            byte[] file = UploadedFilesInSession[index].FileData;
            string fileName = UploadedFilesInSession[index].FileName;
            string fileExtension = fileName.Substring(fileName.Length - 3);

            //Resize Image to thumbnail size if too big
            byte[] resizedImage = ImageUtilities.GetThumbnail(file, Convert.ToInt32(ConfigurationManager.AppSettings["ThumbnailWidth"]));

            var result = new FileContentResult(resizedImage, string.Format("image/{0}", fileExtension));

            return result;
        }

    }
}
